﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PerformanceProfiler
{
    public class ExecutionReport
    {
        private ExecutionReport()
        {
            InstanceRecord = new List<InstanceExecutionRecord>();
            Records = new Dictionary<string, InstanceExecutionRecord>();
        }

        public List<InstanceExecutionRecord> InstanceRecord { get; set; }
        public Dictionary<string, InstanceExecutionRecord> Records { get; set; }

        public static InstanceExecutionRecord GetInstanceRecord(string name)
        {
            var report = Instance;
            InstanceExecutionRecord instancerecord = null;
            if (!report.Records.TryGetValue(name, out instancerecord))
            {
                instancerecord = new InstanceExecutionRecord { InstanceName = name };
                report.Records[name] = instancerecord;
            }
            return instancerecord;
        }

        #region Singleton

        private static object _lock = new object();
        private static ExecutionReport instance = null;
        public static ExecutionReport Instance
        {
            get
            {
                lock (_lock)
                {
                    if (instance == null)
                        instance = new ExecutionReport();
                }
                return instance;
            }
        }

        #endregion
    }

    public class InstanceExecutionRecord
    {
        public InstanceExecutionRecord()
        {
            MemberRecords = new Dictionary<string, MemberExecutionRecord>();
        }

        public string InstanceName { get; set; }
        public Dictionary<string, MemberExecutionRecord> MemberRecords { get; set; }

        public void AddMemberRecord(string name, double start, double total)
        {
            MemberExecutionRecord record = null;
            if (!MemberRecords.TryGetValue(name, out record))
            {
                record = new MemberExecutionRecord { MemberName = name };
                MemberRecords[name] = record;
            }
            record.Executions.Add(new ExecutionRecord { StartTime = start, ExecutionTime = total });
        }
    }

    public class MemberExecutionRecord
    {
        public MemberExecutionRecord()
        {
            Executions = new List<ExecutionRecord>();
        }

        public string MemberName { get; set; }
        public List<ExecutionRecord> Executions { get; set; }
    }

    /// <summary>
    /// This class contains the start and execution times in microseconds
    /// of a single member call.
    /// </summary>
    public class ExecutionRecord
    {
        public double StartTime { get; set; }
        public double ExecutionTime { get; set; }
    }
}
